package com.albert.core.listener;

import com.albert.core.mapper.DictMapper;
import com.albert.core.pojo.dto.ExcelDictDto;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelDictListener extends AnalysisEventListener<ExcelDictDto> {
    //数据列表
    List<ExcelDictDto> list = new ArrayList<>();

    static final int batchCount = 5;
    //因为本类不是spring对象,所以不能使用autowired注解注入,在此处使用构造注入
    private DictMapper dictMapper;
    public ExcelDictListener(DictMapper dictMapper){
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDto data, AnalysisContext analysisContext) {
        log.info("解析一条数据",data);
        list.add(data);
        if(list.size()>=batchCount){
            saveData();
            list.clear();
        }
    }

    /*所有数据解析完成都回来调用*/
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当最后剩余的记录数据不足5,最终一次性存储
        saveData();
        log.info("所有数据解析完成");
    }
    public void saveData(){
        log.info("{}条数据被存储到数据库",list.size());
        //调用mapper层方法
        dictMapper.insertBatch(list);
    }

}
